<?php

namespace App\Kuafu\Shop\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Shop\Enum\AreaCodeEnum;


class AreaModel extends BaseModel
{
    use KfSoftDeletes;

    protected $connection = 'mysql';

    protected $table = 'area';


    public static function getAreaDetail($province, $city, $district)
    {
        return self::query()->where('areaId', $province)
            ->with(['cityRel'=>function($query)use($city, $district){
                $query->where('areaId', $city)->with(['distinctRel'=>function($query)use ($district){
                    $query->where('areaId', $district);
                }]);
            }])->first();
    }

    public function cityRel()
    {
        return $this->hasOne(self::class, 'areaPid', 'areaId');
    }

    public function distinctRel()
    {
        return $this->hasOne(self::class, 'areaPid', 'areaId');
    }

    public function getAreaIdByAdCode(int $adCode): int
    {
        return (int)self::query()->where('adCode', $adCode)->value('areaId');
    }

    public function getFullCode(int $regionCode): array
    {
        $cityCode     = (int)self::query()
                                 ->where('areaId', $regionCode)
                                 ->value('areaPid') ?? 0;
        $provinceCode = (int)self::query()
                                 ->where('areaId', $cityCode)
                                 ->value('areaPid') ?? 0;

        return [$provinceCode, $cityCode, $regionCode];
    }

    /**
     * 通过高德城市编码+区域名称，获取areaId
     * @param int $adCityCode
     * @param string $regionName
     * @return int
     */
    public function getAreaByCityCodeRegionName(int $adCityCode, string $regionName): int
    {
        $cityAreaId = (int)self::query()
                               ->where('level', AreaCodeEnum::AREA_CITY)
                               ->where('adCode', $adCityCode)
                               ->value('areaId');
        if (!$cityAreaId) {
            return 0;
        }

        return (int)self::query()
                        ->where('level', AreaCodeEnum::AREA_AREA)
                        ->where('areaPid', $cityAreaId)
                        ->where('cnShortName', $regionName)
                        ->value('areaId');

    }
}
